package com.rs.portal.reserve.web;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;

import com.jaxplat.commons.Row;
import com.jaxplat.commons.RowImpl;
import com.jaxplat.exceptions.GeneralException;
import com.rs.commons.ApplyType;
import com.rs.commons.RsErrCode;
import com.rs.commons.web.PortalBaseAction;
import com.rs.rsbiz.doctor.delegate.DoctorScheduleDelegate;
import com.rs.rsbiz.services.ReserveFacade;
import com.rs.rsbiz.services.ReserveFactory;
import com.rs.util.IDCardValidator;
import com.rs.util.RegexUtil;

public class ReserveIvrAction extends PortalBaseAction
{
    private Log log = LogFactory.getLog(getClass());
    private DoctorScheduleDelegate dsDelegate;

    public DoctorScheduleDelegate getDsDelegate()
    {
        return dsDelegate;
    }

    public void setDsDelegate(DoctorScheduleDelegate dsDelegate)
    {
        this.dsDelegate = dsDelegate;
    }

    /**
     * <pre>
     * 第一步：从专家浏览页面进入，传入排班id，加载排班信息，forward到step1页面，
     * 在step1页面中载入专家的排班信息。
     * </pre>
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView apply(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        log.info("aaa");
        Row param = this.parseRequestParametersToRow(request);
        Map attrs = new HashMap();
        if (param.containsKey("ds_id"))
        {

            try
            {
                long dsId = param.getLong("ds_id");
                Row dsInfo = dsDelegate.getDoctorSchedule(dsId);
                if (null != dsInfo)
                {
                    attrs.put("dsInfo", dsInfo);
                    return new ModelAndView("reserve_input", attrs);
                }
            }
            catch (Exception e)
            {
                attrs.put("message", "操作有错误.");
                log.info("操作有错误.", e);
            }

        }
        attrs.put("message", "预约信息不存在");

        return new ModelAndView("error", attrs);

    }

    /**
     * <pre>
     * 接收step1中用户提交的内容到confirmAppy，让用户确认订单内容，这个过程不用提交。
     * forward到step2页面。
     * </pre>
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView confirm(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Map attrs = new HashMap();
        Row param = this.parseRequestParametersToRow(request);

        if (param.containsKey("ds_id"))
        {
            try
            {
                long dsId = param.getLong("ds_id");
                Row dsInfo = dsDelegate.getDoctorSchedule(dsId);
                if (null != dsInfo)
                {
                    List validateResult = this.validateApply(param);
                    if (null != validateResult && validateResult.size() > 0)
                    {
                        attrs.put("dsInfo", dsInfo);
                        attrs.put("validateResult", validateResult);
                        return new ModelAndView("reserve_input", attrs);
                    }
                    else
                    {
                        attrs.put("dsInfo", dsInfo);
                        attrs.put("orderInfo", param);
                        return new ModelAndView("reserve_confirm", attrs);
                    }
                }
            }
            catch (Exception e)
            {
                attrs.put("message", "操作有错误.");
                log.info("操作有错误.", e);
            }

        }

        attrs.put("message", "记录不存在.");

        return new ModelAndView("error", attrs);
    }

    protected List validateApply(Row param) throws GeneralException
    {
        List result = new ArrayList();
        if (null == param.getObject("id_type"))
        {
            result.add("证件类型不能为空.");
        }
        if (null == param.getObject("id_no"))
        {
            result.add("证件号码不能为空.");
        }
        if (null == param.getObject("applicant_name"))
        {
            result.add("患者名称不能为空.");
        }
        if (null == param.getObject("gender"))
        {
            result.add("性别不能为空.");
        }
        if (null == param.getObject("mobile_no"))
        {
            result.add("手机号不能为空.");
        }
        if (result.size() > 0)
        {
            return result;
        }
        IDCardValidator idValidator = new IDCardValidator();
        if ("1".equals(param.getString("id_type")))
        {
            // (!"".equals(IDCardValidator.test(param.getString("id_type").trim())))
            if ("".equals(param.getString("id_type").trim()))
            {
                result.add("无效身份证号码.");
            }
        }
        if (!RegexUtil.isMobileNo(param.getString("mobile_no").trim()))
        {
            result.add("无效手机号码.");
        }

        return result;
    }

    /**
     * step2提交动作，调用ReserveFacade.
     * 
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ModelAndView commit(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Map attrs = new HashMap();
        Row param = this.parseRequestParametersToRow(request);

        if (param.containsKey("ds_id"))
        {
            try
            {
                long dsId = param.getLong("ds_id");
                Row dsInfo = dsDelegate.getDoctorSchedule(dsId);
                if (null != dsInfo)
                {
                    List validateResult = this.validateApply(param);

                    if (null != validateResult && validateResult.size() > 0)
                    {
                        attrs.put("dsInfo", dsInfo);
                        attrs.put("validateResult", validateResult);
                        return new ModelAndView("reserve_input", attrs);
                    }
                    else
                    {
                        Row orderInfo = new RowImpl();
                        orderInfo.putAll(param);

                        // 这里的目的是要区分，是wap,12580还是通过其他方式下的订单。

                        orderInfo.addColumn("apply_type", ApplyType.WAP);

                        orderInfo.addColumn("remote_ip", request.getRemoteAddr());

                        ReserveFacade reserveFacade = ReserveFactory.getReserveFacade();

                        Row applyParam = new RowImpl();
                        applyParam.put("dsInfo", dsInfo);
                        applyParam.put("orderInfo", orderInfo);
                        /**
                         * <pre>
                         * dsInfo,orderInfo，这两个数据非常重要。 
                         * 支付过程中将排班信息和原始订单信息一直传递到整个流程结束。
                         * 在后面还会添加以下几个,
                         * lockedOder: 锁定后的订单信息。
                         * userInfo: 接线员的信息，用于系统管理员为用户录入订单。
                         * 让所有的公共参数流转于整个流程，减少麻烦，使操作过程简洁。
                         * 
                         * </pre>
                         */

                        Row applyResult = reserveFacade.applyReserve(applyParam);
                        if (RsErrCode.SUCCESS.equals(applyResult.getString("errcode")))
                        {
                            attrs.putAll(applyResult);
                            return new ModelAndView("reserve_result", attrs);
                        }
                        else
                        {
                            attrs.putAll(applyResult);
                            return new ModelAndView("error", attrs);
                        }

                    }
                }
            }
            catch (Exception e)
            {
                attrs.put("message", "操作有错误.");
                log.info("操作有错误.", e);
            }

        }

        attrs.put("message", "记录不存在.");

        return new ModelAndView("error", attrs);
    }
}
